package org.feng.resource.impl;

import cn.hutool.core.collection.CollectionUtil;
import org.feng.resource.ResourceUpload;
import org.feng.entity.Resource;
import org.feng.utils.UUIDUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.InputStream;
import java.util.Arrays;

/**
 * @author 冯帅
 * @des TODO
 * @date 2021/11/30 15:50
 * @email 15612509687@163.com
 */
public class QiNiu implements ResourceUpload {

    private Resource resource;
    private Auth auth;
    private BucketManager bucketManager;
    private UploadManager uploadManager;

    public QiNiu(Resource resource) {
        Configuration cfg = new Configuration(Region.autoRegion());
        this.resource = resource;
        this.auth = Auth.create(resource.getKey(), resource.getSecret());
        this.bucketManager = new BucketManager(this.auth, cfg);
        this.uploadManager = new UploadManager(cfg);
    }

    @Override
    public void createBucket(String name) {
        try {
            if (!CollectionUtil.contains(Arrays.asList(bucketManager.buckets()), name)) {
                bucketManager.createBucket(resource.getBucket(), "https://uc.qbox.m");
            }
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void deleteBucket(String name) {
    }

    @Override
    public String putFile(InputStream stream, String fileName, Boolean override) {
        String token = auth.uploadToken(resource.getBucket());
        if (override) {
            try {
                uploadManager.put(stream, fileName, token, null, null);
            } catch (QiniuException e) {
                e.printStackTrace();
            }
        } else {
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUIDUtil.getUUID() + suffix;
            try {
                uploadManager.put(stream, fileName, token, null, null);
            } catch (QiniuException e) {
                e.printStackTrace();
            }
        }
        return getLink(fileName);
    }


    private String getLink(String fileName) {
        return this.resource.getEndpoint() + "/" + fileName;
    }

}
